import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:loadmore/loadmore.dart';
import 'package:xlsk/api/model/banji.dart';
import 'package:xlsk/api/model/student.dart';
import 'package:xlsk/components/checkview.dart';
import 'package:xlsk/components/dropdown.dart';
import 'package:xlsk/components/empty.dart';
import 'package:xlsk/components/search.dart';
import 'package:xlsk/components/tabs.dart';
import 'package:xlsk/routes/xlsk_router.dart';
import 'package:xlsk/utils/dimension.dart';

class StudentList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _listState();
  }
}

class _listState extends State<StudentList> {
  int page = 1;
  int limit = 10;
  String banji_id = '';
  List studentList = [];
  List nowStudentList = [''];
  int count = 0;
  bool canLoad = true;
  double contentHeight = 0; //为了防止empty不显示，设置一个默认高度
  String search = '';
  int status = 0;
  List banji = [];
  bool keepShowDropdown = false;

  GlobalKey _anchorKey = GlobalKey();


  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance?.addPostFrameCallback((_) {
      RenderBox renderBox = _anchorKey.currentContext?.findRenderObject() as RenderBox;
      var offset = renderBox.localToGlobal(Offset.zero);
      var _dpHeight = MediaQuery.of(context).size.height;
      setState(() {
        contentHeight = _dpHeight - offset.dy;
      });
      getStudentData();
      getBanji();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("学员管理",style: TextStyle(color: Color(0xFF1F2329),fontSize: Dimension(context).toPx(17),fontWeight: FontWeight.bold)),
        leading: GestureDetector(
          child: Icon(Icons.arrow_back_ios,color: Color.fromRGBO(31, 35, 41, 1),size: 24,),
          onTap: (){
            XlskRouter.back(context);
          },
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      body: RefreshIndicator(
        child: Column(
          children: [
            Container(
              child: Search(343,32,'搜索学员姓名',(value){
                setState(() {
                  search = value;
                  init();
                });
              }),
              width: Dimension(context).toVw(100),
              padding: EdgeInsets.symmetric(vertical: Dimension(context).toPx(8),horizontal: Dimension(context).toPx(16)),
              decoration: BoxDecoration(
                  color: Colors.white
              ),
            ),
            Expanded(
              child: Stack(
                children: [
                  Positioned(
                    left: 0,
                    top: Dimension(context).toPx(48),
                    child: Container(
                      key: _anchorKey,
                      width: Dimension(context).toVw(100),
                      height: contentHeight,
                      decoration: BoxDecoration(
                        color: Color(0xFFF7F8FA)
                      ),
                      child: studentList.length > 0?Align(
                        alignment: Alignment.topCenter,
                        child: Container(
                          width: Dimension(context).toPx(343),
                          child: LoadMore(
                            isFinish: nowStudentList.length == 0?true:false,
                            onLoadMore: getStudentData,
                            child: ListView.builder(
                              itemCount: count,
                              itemBuilder: (BuildContext context,int index){
                                return GestureDetector(
                                  onTap: (){
                                    XlskRouter.go(context, '/student/info?id=${studentList[index]['id']}');
                                  },
                                  child: Container(
                                    width: Dimension(context).toPx(343),
                                    padding: EdgeInsets.only(top: Dimension(context).toPx(16),bottom: Dimension(context).toPx(16),left: Dimension(context).toPx(16)),
                                    margin: EdgeInsets.only(top: Dimension(context).toPx(16)),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(Dimension(context).toPx(12)))
                                    ),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            Text('${studentList[index]['name']}',style: TextStyle(fontSize: Dimension(context).toPx(18),fontWeight: FontWeight.w700,color: Color(0xff1f2329))),
                                            Container(
                                              width: Dimension(context).toPx(30),
                                              height: Dimension(context).toPx(19),
                                              margin: EdgeInsets.only(left: Dimension(context).toPx(12)),
                                              decoration: BoxDecoration(
                                                  color: num.parse(studentList[index]['status']) == 1?Color(0xffe6f2ff):Color(0xfff7f8fa),
                                                  borderRadius: BorderRadius.all(Radius.circular(Dimension(context).toPx(4)))
                                              ),
                                              child: Center(
                                                child: Text('${num.parse(studentList[index]['status']) == 1?'在读':'历史'}',style: TextStyle(color: num.parse(studentList[index]['status']) == 1?Color(0xff1661ff):Color(0xff8f959e),fontSize: Dimension(context).toPx(11))),
                                              ),
                                            )
                                          ],
                                        ),
                                        Container(
                                          margin: EdgeInsets.only(top: Dimension(context).toPx(8)),
                                          child: Text('${studentList[index]['bjname']}',style: TextStyle(color: Color(0xff646a73),fontSize: Dimension(context).toPx(15))),
                                        ),
                                        Container(
                                          width: Dimension(context).toPx(200),
                                          margin: EdgeInsets.only(top: Dimension(context).toPx(8)),
                                          child: Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text('剩余课时：${studentList[index]['left_lession']['left_lession']}课时',style: TextStyle(color: Color(0xff8f959e),fontSize: Dimension(context).toPx(12))),
                                              Text('剩余天数：${studentList[index]['left_lession']['left_day']}天',style: TextStyle(color: Color(0xff8f959e),fontSize: Dimension(context).toPx(12))),
                                            ],
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                        ),
                      ):Empty('暂无学员'),
                    ),
                  ),
                  Positioned(
                    left: 0,
                    top: 0,
                    child: Dropdown(
                      keepShow: keepShowDropdown,
                      contentHeight: contentHeight,
                      maxHeight: 230,
                      textHeight: 40,
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Checkview(
                              isMore: true,
                              title: '班级(可多选)',
                              list: banji,
                              checkedId: banji_id,
                              onChange: (id){
                                setState(() {
                                  keepShowDropdown = true;
                                  banji_id = id;
                                });
                              },
                            )
                          ],
                        )
                      ],
                      finish: (){
                        setState(() {
                          keepShowDropdown = false;
                          init();
                        });
                      },
                      resert: (){
                        setState(() {
                          keepShowDropdown = true;
                          banji_id = '';
                        });
                      },
                    )
                  ),
                  Positioned(
                    left: 0,
                    top: 0,
                    child: Tabs(
                      tabList: ['全部','在读','历史'],
                      width: 200,
                      current: status,
                      canMove: canLoad,
                      callback: (res){
                        setState(() {
                          status = res;
                          init();
                        });
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        onRefresh: () async{
          init();
        },
      ),
    );
  }

  void init(){
    setState(() {
      page = 1;
      studentList = [];
      nowStudentList = [];
      getStudentData();
    });
  }

  Future<bool> getStudentData() async{
    if(!canLoad){return false;}
    canLoad = false;
    List _studentList = studentList;
    int _page = page;
    Map <String,dynamic> data = {
      'page':page,
      'limit':limit,
    };
    if(search != ''){
      data['search'] = search;
    }
    if(status > 0){
      data['status'] = status;
    }
    if(banji_id != ''){
      data['banji_id'] = banji_id;
    }
    // print('data');print(data);
    var res = await StudentApi().getStudent(context, '/student', data);
    if(res.length > 0){
      _page++;
    }
    _studentList.addAll(res);
    setState(() {
      studentList = _studentList;
      nowStudentList = res;
      page = _page;
    });
    setState(() {
      count = _studentList.length;
    });
    canLoad = true;
    return true;
  }

  getBanji() async{
    var res = await BanjiApi().getBanji(context, '/Banji/index');
    List<dynamic> banjiList = [];
    for(var item in res){
      Map<String,dynamic> m = {
        'id':item['id'],
        'title':item['name']
      };
      banjiList.add(m);
    }
    setState(() {
      banji = banjiList;
    });
  }

  @override
  void dispose() {
    super.dispose();
  }
}

